// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next';
import dayjs from 'dayjs';
import { BeError, BeSuccess, ResponseDataType } from '@/utils/response';
import { tongzhiFEDD } from '@/services/dingtalk/func';

type TapdData = {
  id: string;
  name: string;
  user: string;
  timestamp_micro: number;
};

export default async function handler(req: NextApiRequest, res: NextApiResponse<ResponseDataType>) {
  if (req.method?.toLowerCase() !== 'post') {
    res.status(200).json(BeError('不支持请求类型'));
    res.end();
    return;
  }
  const { event } = req.body;
  const { user, name, timestamp_micro: timestampMicro, id }: TapdData = event;
  try {
    // `需求${name}，提测人${user},提测时间${timestamp_micro}`;
    await tongzhiFEDD(id, `提测:${name}`, [`提测人:${user}`, `提测时间${dayjs(timestampMicro).format('YYYY-MM-DD HH:mm:ss')}`]);
    res.status(200).json(BeSuccess());
  } catch (err: any) {
    console.error(err);
    res.status(200).json(BeError(err));
  }
  res.end();
}
